import React from 'react'
import PropTypes from 'prop-types'
import { routerRedux } from 'dva/router'
import { connect } from 'dva'
import { Page } from 'components'
import queryString from 'query-string'
import List from './List'
import Filter from './Filter'
import Modal from './Modal'

const Message = ({
  location, dispatch, message, loading,
}) => {
  location.query = queryString.parse(location.search)
  const { query, pathname } = location
  const {
    list, pagination, currentItem, modalVisible,
  } = message
  const { pageSize } = pagination

  const modalProps = {
    item: currentItem,
    visible: modalVisible,
    maskClosable: false,
    title: '消息详情',
    wrapClassName: 'vertical-center-modal',
    onOk () {
      dispatch({
        type: 'message/hideModal',
      })
    },
    onCancel () {
      dispatch({
        type: 'message/hideModal',
      })
    },
  }

  const listProps = {
    dataSource: list,
    loading: loading.effects['message/query'],
    pagination,
    location,
    onChange (page) {
      dispatch(routerRedux.push({
        pathname,
        search: queryString.stringify({
          ...query,
          page: page.current,
          pageSize: page.pageSize,
        }),
      }))
    },
    onDeleteItem (param) {
      dispatch({
        type: 'message/delete',
        payload: param,
      })
    },
    onInfoItem (param) {
      dispatch({
        type: 'message/info',
        payload: {
          id: param.id,
        },
      })
    },
  }

  const filterProps = {
    filter: {
      ...query,
    },
    onFilterChange (value) {
      dispatch(routerRedux.push({
        pathname: location.pathname,
        search: queryString.stringify({
          ...value,
          page: 1,
          pageSize,
        }),
      }))
    },
    onSearch (fieldsValue) {
      fieldsValue.keyword.length ? dispatch(routerRedux.push({
        pathname: '/message',
        query: {
          field: fieldsValue.field,
          keyword: fieldsValue.keyword,
        },
      })) : dispatch(routerRedux.push({
        pathname: '/message',
      }))
    },
    switchIsMotion () {
      dispatch({ type: 'message/switchIsMotion' })
    },
  }

  return (
    <Page inner>
      <Filter {...filterProps} />
      <List {...listProps} />
      {modalVisible && <Modal {...modalProps} />}
    </Page>
  )
}

Message.propTypes = {
  message: PropTypes.object,
  location: PropTypes.object,
  dispatch: PropTypes.func,
  loading: PropTypes.object,
}

export default connect(({ message, loading }) => ({ message, loading }))(Message)
